package filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

/**
 * 字符编码过滤器
 * 1.实现javax.servlet.Filter接口
 * 2.重写 init  doFilter destroy
 * 3.在doFilter 进行过滤操作，如果放行则调用filterChain.doFilter(servletRequest,servletResponse);
 *
 *
 *
 */
@WebFilter(urlPatterns = "/servlet/*")
public class EncodingFilter implements Filter {
    private String encoding=null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("初始化时读取上下文中的配置参数......");
        encoding= filterConfig.getServletContext().getInitParameter("encoding");
        System.out.println(encoding);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter......");
        if(encoding!=null){
            servletRequest.setCharacterEncoding(encoding);
        }
        servletResponse.setContentType("text/html;charset=UTF-8");
        //放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        System.out.println("销毁......");
        this.encoding=null;
    }
}
